﻿using IceDog.Lib.Poker.PokerEventHandler;
using IceDog.Lib.Poker.PokerException;
using System;

namespace IceDog.Lib.Poker
{
    public class Deck:ICloneable
    {
        private CardList _cardList;

        public Deck()
        {
            _cardList = new CardList();
            for (int i = 1; i <= 4; i++)
            {
                for (int j = 1; j <= 13; j++)
                {
                    _cardList.Add(new Card((Suit)i, (Rank)j));
                }
            }
        }

        public Deck(bool isAceHigh):this()
        {
            Card.isAceHigh = isAceHigh;
        }
        public Deck(bool useTrump, Suit trump):this()
        {
            Card.useTrump = useTrump;
            Card.trump = trump;
        }
        public Deck(bool isAceHigh, bool useTrump, Suit trump) :this()
        {
            Card.isAceHigh = isAceHigh;
            Card.useTrump = useTrump;
            Card.trump = trump;
        }
        private Deck(CardList list)
        {
            this._cardList = list;
        }
        /// <summary>
        /// 洗牌操作
        /// </summary>
        public void Shuffle()
        {
            var flag = new bool[52];
            var newDeck = new CardList();
            var ran = new Random();
            for (int i = 0; i < 52; i++)
            {
                var index = 0;
                var foundCard = false;
                while (!foundCard)
                {
                    index = ran.Next(52);
                    if (!flag[index])
                    {
                        foundCard = true;
                    }
                }
                flag[index] = true;
                newDeck.Add(_cardList[index]);
            }
            newDeck.CopyTo(_cardList);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="num">值只能在1到52之间(包括1和52)</param>
        /// <returns></returns>
        public Card GetCard(int num)
        {
            if (num>0&&num<53)
            {
                if (num.Equals(52)&&LastCardDrawn!=null)
                {
                    LastCardDrawn(this,new LastCardDrawnEventHandler());
                }
                return _cardList[num-1];
            }
            else
            {
                throw new CardOutOfRangeException(_cardList.Clone() as CardList);
            }
        }

        public object Clone()
        {
            return new Deck(_cardList.Clone() as CardList);
        }

        public event EventHandler<LastCardDrawnEventHandler> LastCardDrawn;
    }
}
